package com.wohuijituan.whcsmerchant.fragment;


import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.activity.ShopGoodsSearchActivity;
import com.wohuijituan.whcsmerchant.adapter.GoodsCategoryAAdapter;
import com.wohuijituan.whcsmerchant.adapter.GoodsCategoryBAdapter;
import com.wohuijituan.whcsmerchant.bean.GoodsCategoryABCData;
import com.wohuijituan.whcsmerchant.bean.GoodsCategoryBCData;
import com.wohuijituan.whcsmerchant.bean.GoodsCategoryBean;
import com.wohuijituan.whcsmerchant.callback.GoodsCategoryCallBack;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyOkHttpUtils;
import com.wohuijituan.whcsmerchant.utils.MyRequestParams;
import com.wohuijituan.whcsmerchant.utils.MyUtile;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * A simple {@link MyBaseFragment} subclass.
 */
public class GoodsFragment extends MyBaseFragment implements View.OnClickListener {
    private static final String TAG = "GoodsFragment";
    private static final int GoodsCategory_OK = 130;
    private ListView lvGoodsCategoryA;
    private ListView lvGoodsCategoryB;
    private GoodsCategoryAAdapter mAdapterA;
    private GoodsCategoryBAdapter mAdapterB;
    private List<GoodsCategoryABCData> categoryABCList;
    private List<GoodsCategoryBCData> categoryBCList;
    private LinearLayout llSearch;
    private ImageButton titleGoBack;
    private TextView titleName;
    private TextView titleTvAction;
    private ImageButton titleIbAction;
    private RelativeLayout title;

    private void assignViews(View v) {
        lvGoodsCategoryA = (ListView) v.findViewById(R.id.lv_goods_category_a);
        lvGoodsCategoryB = (ListView) v.findViewById(R.id.lv_goods_category_b);
        llSearch = (LinearLayout) v.findViewById(R.id.ll_search);
        titleGoBack = (ImageButton) v.findViewById(R.id.title_go_back);
        titleName = (TextView) v.findViewById(R.id.title_name);
        titleTvAction = (TextView) v.findViewById(R.id.title_tv_action);
        titleIbAction = (ImageButton) v.findViewById(R.id.title_ib_action);
        title = (RelativeLayout) v.findViewById(R.id.title);
    }

    private MyOkHttpUtils myOkHttpUtils;
    private MyRequestParams params;

    @Override
    public View createMyView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_goods, container, false);
        assignViews(view);
        iniData();
        initView();
        initListener();
        getGoodsCategory(SYSTEM_SORT_LIST);
        return view;
    }
    private void iniData() {
        myOkHttpUtils = new MyOkHttpUtils();
        params = new MyRequestParams();
        //给a列表添加数据
        categoryABCList = new ArrayList<>();
        mAdapterA = new GoodsCategoryAAdapter(ctx, categoryABCList);
        lvGoodsCategoryA.setAdapter(mAdapterA);
        //初始化b列表
        categoryBCList = new ArrayList<>();
        mAdapterB = new GoodsCategoryBAdapter(ctx, categoryBCList);
        lvGoodsCategoryB.setAdapter(mAdapterB);
    }

    private void initView() {
        titleIbAction.setVisibility(View.VISIBLE);
        titleName.setText("系统类别列表");
    }

    private void initListener() {
        //给列表a添加监听
        titleIbAction.setOnClickListener(this);
        llSearch.setOnClickListener(this);
        lvGoodsCategoryA.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mAdapterA.setCheckStyle(position);//设置选中状态样式
                List<GoodsCategoryBCData> strings = getBCategoryList(position);//获取对应一级下的二级列表
                mAdapterB.replace(strings);//替换mAdapterB中数据
                LogUtils.e(TAG, "position:" + position);
                lvGoodsCategoryB.setSelection(0);//b列表回到顶部
            }
        });
    }

    /**
     * 得到一级列表下的二级种类列表
     *
     * @param position
     * @return 二级种类列表
     */
    private List<GoodsCategoryBCData> getBCategoryList(int position) {
        // 得到一级列表下的二级种类列表
        List<GoodsCategoryBCData> bcDatas = new ArrayList<>();
        bcDatas = categoryABCList.get(position).getCategoryBCList();
        return bcDatas;
    }
    /**
     * 网络请求获得商品类别数据
     */
    private void getGoodsCategory(int sortStyle) {
        showDialog(ctx);
        GoodsCategoryCallBack callBack = new GoodsCategoryCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(GoodsCategoryBean response, int id) {
                if (response.getState() == 1) {
                    Message msg = new Message();
                    msg.what = GoodsCategory_OK;
                    Bundle data = new Bundle();
                    msg.obj = response;
                    handler.sendMessage(msg);
                } else if (response.getState() == 0) {
                    dismissDialog();
                    showToast(ctx, "服务器数据为空");
                } else {
                    showToast(ctx, response.getMsg());
                    dismissDialog();
                }
            }
        };
        String strUrl;
        if (sortStyle==MY_SORT_LIST){
            strUrl = Urls.MyGoodsCategory;
            params.addStringRequest(ParamsKey.GetSMCate_Guid,myApplication.getUserKey());
            myOkHttpUtils.postRequest(strUrl,params,callBack);
        }else {
            strUrl = Urls.GoodsCategory;
            myOkHttpUtils.okHttpGet(strUrl,callBack );
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GoodsCategory_OK:
                    //得到商品分类的bean
                    GoodsCategoryBean dataBean = (GoodsCategoryBean) msg.obj;
                    //把商品类别分成三级结构
                    List<GoodsCategoryABCData> dataList = MyUtile.turnToABC(dataBean.getData());
                    mAdapterA.replace(dataList);
                    mAdapterA.setCheckStyle(0);
                    mAdapterB.replace(dataList.get(0).getCategoryBCList());
                    dismissDialog();
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_ib_action:
                //  弹出选择框
                showPopWind();
                break;
            case R.id.ll_search:
                // 2016/12/25 进入搜索页面
                LogUtils.e(TAG,"ll_search");
                Intent intent = new Intent(ctx, ShopGoodsSearchActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_system_goods_sort:
                //  2016/12/25 选择系统商品列表的时候进行的动作
                setGoodsSortSytel(SYSTEM_SORT_LIST);
                getGoodsCategory(SYSTEM_SORT_LIST);
                popupWindow.dismiss();
                break;
            case R.id.tv_my_goods_sort:
                // 2016/12/25 选择我的商品列表的时候进行的动作
                getGoodsCategory(MY_SORT_LIST);
                setGoodsSortSytel(MY_SORT_LIST);
                popupWindow.dismiss();
                break;
        }
    }

    private static final int SYSTEM_SORT_LIST = 1;
    private static final int MY_SORT_LIST = 2;

    private void setGoodsSortSytel(int sortListStyle) {
        if (sortListStyle == SYSTEM_SORT_LIST) {
            titleName.setText("系统类别列表");
        } else {
            titleName.setText("我的类别列表");
        }
    }

    private PopupWindow popupWindow;
    private TextView tvSystemGoodsSort, tvMyGoodsSort;

    /**
     * 显示弹出框PopWindow
     */
    private void showPopWind() {
        if (popupWindow == null) {
            View v = View.inflate(ctx, R.layout.pop_goods_sort_type, null);
            tvSystemGoodsSort = (TextView) v.findViewById(R.id.tv_system_goods_sort);
            tvMyGoodsSort = (TextView) v.findViewById(R.id.tv_my_goods_sort);
            tvSystemGoodsSort.setOnClickListener(this);
            tvMyGoodsSort.setOnClickListener(this);
            popupWindow = new PopupWindow(v, WindowManager.LayoutParams.WRAP_CONTENT,
                    WindowManager.LayoutParams.WRAP_CONTENT, true);
            popupWindow.setFocusable(true);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setBackgroundDrawable(new BitmapDrawable());
        }
        popupWindow.showAsDropDown(titleIbAction, 0, (title.getHeight() - titleIbAction.getHeight()) / 2);
    }
}
